import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/auth/Login.vue'),
      meta: { requiresGuest: true }
    },
    {
      path: '/',
      name: 'Layout',
      component: () => import('@/views/Layout.vue'),
      meta: { requiresAuth: true },
      redirect: '/dashboard',
      children: [
        {
          path: '/dashboard',
          name: 'Dashboard',
          component: () => import('@/views/Dashboard.vue'),
          meta: { title: '仪表盘' }
        },
        {
          path: '/news',
          name: 'NewsList',
          component: () => import('@/views/news/NewsList.vue'),
          meta: { title: '新闻管理' }
        },
        {
          path: '/news/create',
          name: 'NewsCreate',
          component: () => import('@/views/news/NewsForm.vue'),
          meta: { title: '创建新闻' }
        },
        {
          path: '/news/edit/:id',
          name: 'NewsEdit',
          component: () => import('@/views/news/NewsForm.vue'),
          meta: { title: '编辑新闻' }
        },
        {
          path: '/categories',
          name: 'CategoryList',
          component: () => import('@/views/category/CategoryList.vue'),
          meta: { title: '分类管理' }
        }
      ]
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('@/views/NotFound.vue')
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 需要登录的页面
  if (to.meta.requiresAuth && !userStore.isAuthenticated) {
    next('/login')
    return
  }
  
  // 已登录用户访问登录页面，重定向到首页
  if (to.meta.requiresGuest && userStore.isAuthenticated) {
    next('/')
    return
  }
  
  next()
})

export default router
